/*
 * $HeadURL: $
 * $Id: $
 * Copyright (c) 2012 by Wodensoft System, all rights reserved.
 */
package com.wodensoft.util.script.impl;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.lang.MissingMethodException;
import groovy.lang.MissingPropertyException;

import java.util.Map;

import org.codehaus.groovy.control.MultipleCompilationErrorsException;

import com.wodensoft.util.script.ExecutionContext;
import com.wodensoft.util.script.ExecutionException;
import com.wodensoft.util.script.ScriptExecutor;

/**
 * @author Borball
 * 
 */
public class GroovyScriptEngine implements ScriptExecutor {

    private GroovyShell shell;
    private Binding bindings;

    public GroovyScriptEngine(Map<String, Object> functions) {
        bindings = new Binding();
        if (functions != null) {
            for (String funcName : functions.keySet()) {
                bindings.setProperty(funcName, functions.get(funcName));
            }
        }
        shell = new GroovyShell(bindings);
    }

    @Override
    public Object evaluateScript(String script, ExecutionContext context) throws ExecutionException{
        setShellContext(context);
        try{
            return shell.evaluate(script);
        } catch (MissingPropertyException ex){
            throw new ExecutionException("属性:" + ex.getProperty() + "不存在,请检查脚本.");
        } catch (MissingMethodException ex){
            throw new ExecutionException("方法:" + ex.getMethod() + "不存在,请检查脚本.");
        } catch (MultipleCompilationErrorsException ex){
            throw new ExecutionException("编译脚本出错:" + ex.getMessage());
        } catch (Exception ex){
            throw new ExecutionException("其他错误:" + ex.getMessage());
        }
    }

    private void setShellContext(ExecutionContext context) {
        if (context.getVariableContext() == null || context.getVariableContext().isEmpty())
            return;
        for (String varName : context.getVariableContext().keySet()) {
            shell.setVariable(varName, context.getVariableContext().get(varName));
        }
    }

}
